<template>
  <div class="admin-feedback-list">
    <h2>后台管理 - 意见列表</h2>
    <button @click="fetchFeedback" :disabled="loading">
      {{ loading ? '加载中...' : '刷新列表' }}
    </button>
    <div v-if="error" class="error-message">{{ error }}</div>

    <div v-if="selectedFeedback" class="modal-overlay" @click.self="selectedFeedback = null">
      <div class="modal-content">
        <h3>处理反馈 ID: {{ selectedFeedback.id }}</h3>
        <p><strong>提交者:</strong> {{
            selectedFeedback.is_anonymous ? '匿名' : `${selectedFeedback.submitter_name} (${selectedFeedback.submitter_phone})`
          }}</p>
        <p><strong>地点:</strong> {{ selectedFeedback.location }}</p>
        <p><strong>内容:</strong> {{ selectedFeedback.feedback_content }}</p>
        <p><strong>提交时间:</strong> {{ formatTimestamp(selectedFeedback.submission_timestamp) }}</p>
        <hr/>
        <form @submit.prevent="handleUpdate(selectedFeedback.id)">
          <div>
            <label for="category1">分类一:</label>
            <select id="category1" v-model="editForm.category1">
              <option value="">请选择</option>
              <option v-for="cat in categories1" :key="cat" :value="cat">{{ cat }}</option>
            </select>
          </div>
          <div>
            <label for="category2">分类二:</label>
            <select id="category2" v-model="editForm.category2">
              <option value="">请选择</option>
              <option v-for="cat in categories2" :key="cat" :value="cat">{{ cat }}</option>
            </select>
          </div>
          <div>
            <label for="assigned_department">指派部门:</label>
            <input type="text" id="assigned_department" v-model="editForm.assigned_department"/>
          </div>
          <div>
            <label for="status">状态:</label>
            <select id="status" v-model="editForm.status">
              <option value="已提交">已提交</option>
              <option value="处理中">处理中</option>
              <option value="已回复">已回复</option>
              <option value="已关闭">已关闭</option>
            </select>
          </div>
          <div>
            <label for="department_reply">回复读者:</label>
            <textarea id="department_reply" v-model="editForm.department_reply" rows="3"></textarea>
          </div>
          <button type="submit" :disabled="updating">
            {{ updating ? '更新中...' : '更新反馈' }}
          </button>
          <button type="button" @click="selectedFeedback = null" style="margin-left: 10px;">取消</button>
        </form>
        <div v-if="updateMessage" :class="updateMessageType === 'success' ? 'success-message' : 'error-message'">
          {{ updateMessage }}
        </div>
      </div>
    </div>

    <table>
      <thead>
      <tr>
        <th>ID</th>
        <th>内容摘要</th>
        <th>地点</th>
        <th>读者姓名</th>
        <th>读者电话</th>
        <th>提交时间</th>
        <th>状态</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="fb in feedbackList" :key="fb.id">
        <td>{{ fb.id }}</td>
        <td>{{ fb.feedback_content.substring(0, 50) }}...</td>
        <td>{{ fb.location }}</td>

        <td v-if="fb.is_anonymous">
          <span style="color: grey;">(匿名提交)</span>
        </td>
        <td v-else>
          {{ fb.full_name || '(未提供)' }}
        </td>

        <td v-if="fb.is_anonymous">
          <span style="color: grey;">-</span>
        </td>
        <td v-else>
          {{ fb.phone_number || '(未提供)' }}
        </td>

        <td>{{ formatTimestamp(fb.submission_timestamp) }}</td>
        <td>{{ fb.status }}</td>
        <td>
          <button @click="openEditModal(fb)">查看/处理</button>
        </td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import api from '@/services/api';

export default {
  name: 'AdminFeedbackList',
  data() {
    return {
      feedbackList: [],
      loading: false,
      error: '',
      selectedFeedback: null, // 用于弹窗编辑
      editForm: {
        category1: '',
        category2: '',
        assigned_department: '',
        status: '',
        department_reply: '',
      },
      updating: false,
      updateMessage: '',
      updateMessageType: '',
      categories1: [ // 从需求文档中获取
        '借阅服务', '网站服务', '活动', '工作人员',
        '逾期费/积分制', '座位预约', '阅览座席', '其他'
      ],
      categories2: [ // 从需求文档中获取
        '设备设施', '电子设备/wifi', '光线', '气味', '声音', '温度'
      ]
    };
  },
  created() {
    this.fetchFeedback();
  },
  methods: {
    async fetchFeedback() {
      this.loading = true;
      this.error = '';
      try {
        const response = await api.getAllFeedback();
        this.feedbackList = response.data;
      } catch (err) {
        this.error = '加载反馈列表失败。请检查后端服务是否开启，或网络连接。';
        console.error('Error fetching feedback list:', err);
      } finally {
        this.loading = false;
      }
    },
    openEditModal(feedback) {
      this.selectedFeedback = feedback;
      // 将当前反馈的值填充到编辑表单
      this.editForm = {
        category1: feedback.category1 || '',
        category2: feedback.category2 || '',
        assigned_department: feedback.assigned_department || '',
        status: feedback.status || 'Submitted',
        department_reply: feedback.department_reply || '',
      };
      this.updateMessage = ''; // 清除旧的更新消息
    },
    async handleUpdate(feedbackId) {
      this.updating = true;
      this.updateMessage = '';
      try {
        const response = await api.updateFeedback(feedbackId, this.editForm);
        this.updateMessageType = 'success';
        this.updateMessage = response.data.message || '更新成功!';
        // 更新成功后，刷新列表或直接更新列表中的对应项
        await this.fetchFeedback(); // 简单起见，重新加载整个列表
        // 也可以选择延迟关闭弹窗，或在用户确认后关闭
        // setTimeout(() => { this.selectedFeedback = null; }, 2000);
      } catch (error) {
        this.updateMessageType = 'error';
        if (error.response && error.response.data && error.response.data.error) {
          this.updateMessage = error.response.data.error;
        } else {
          this.updateMessage = '更新失败。';
        }
        console.error('Error updating feedback:', error);
      } finally {
        this.updating = false;
      }
    },
    formatTimestamp(timestamp) {
      if (!timestamp) return '';
      return new Date(timestamp).toLocaleString('zh-CN');
    }
  },
};
</script>

<style scoped>
.admin-feedback-list {
  margin: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
}

.error-message {
  color: red;
  margin-top: 10px;
}

/* Modal styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-content h3 {
  margin-top: 0;
}

.modal-content div {
  margin-bottom: 10px;
}

.modal-content label {
  display: block;
  margin-bottom: 3px;
  font-weight: bold;
}

.modal-content input[type="text"],
.modal-content select,
.modal-content textarea {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 4px;
}

/* ... (add more styles for success/error messages within modal if needed) ... */
.success-message {
  color: green;
}

.error-message {
  color: red;
}
</style>